import { reactive } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getProcessVersion,
  getApprovalHistory as fetchApprovalHistory,
  getNodeStatus,
  startProcess as startProcessApi,
  getProcessVersionById,
  getNextNodes,
  submitApproval as submitApprovalApi
} from '@/api/workflow/process.api'
import { getProcessFormBindList } from '@/api/workflow/processFormBind.api'
import { getFormDetail } from '@/api/workflow/form.api'
import { getFormDataByInstanceId } from '@/api/workflow/formData.api'

// 数据状态接口
export interface ProcessDetailData {
  formData: any
  graphData: any
  approvalHistory: any[]
  nodeStatusList: any[]
  assigneeData: any[]
  nextNodes: any[]
  diagramLoaded: boolean
  dataLoaded: {
    form: boolean
    diagram: boolean
    history: boolean
    status: boolean
    nextNodes: boolean
  }
}

// 初始化数据管理器
export class ProcessDetailDataManager {
  private data: ProcessDetailData
  private callbacks: {
    onDataChange?: (data: ProcessDetailData) => void
    onSuccess?: (action: string, result: any) => void
    onError?: (action: string, error: any) => void
  } = {}
  private isInitializing = false // 添加初始化状态标志
  private isStartingProcess = false // 添加流程发起状态标志

  constructor() {
    this.data = reactive({
      formData: null,
      graphData: null,
      approvalHistory: [],
      nodeStatusList: [],
      assigneeData: [],
      nextNodes: [],
      diagramLoaded: false,
      dataLoaded: {
        form: false,
        diagram: false,
        history: false,
        status: false,
        nextNodes: false
      }
    })
  }

  // 设置回调函数
  setCallbacks(callbacks: typeof this.callbacks) {
    this.callbacks = { ...this.callbacks, ...callbacks }
  }

  // 表单数据变化处理
  onFormDataChange(newFormData: any) {
    // 检查是否是事件对象，如果是则忽略
    if (newFormData && typeof newFormData === 'object' && newFormData.target && newFormData.type) {
      console.log('ProcessDetailDataManager - 接收到事件对象，忽略')
      return
    }

    // 确保是有效的表单数据
    if (newFormData && typeof newFormData === 'object') {
      // 更新表单数据
      if (this.data.formData) {
        this.data.formData.formData = newFormData
      } else {
        this.data.formData = { formData: newFormData }
      }

      // 通知回调，触发网关条件重新计算
      this.callbacks.onDataChange?.(this.data)
    }
  }

  // 获取数据
  getData(): ProcessDetailData {
    return this.data
  }

  // 重置数据
  resetData() {
    this.data.formData = null
    this.data.approvalHistory = []
    this.data.nodeStatusList = []
    this.data.graphData = null
    this.data.assigneeData = []
    this.data.nextNodes = []
    this.data.diagramLoaded = false
    this.data.dataLoaded = {
      form: false,
      diagram: false,
      history: false,
      status: false,
      nextNodes: false
    }
  }

  // 初始化所有数据
  async initializeData(displayData: any, mode: string) {
    console.log('ProcessDetailDataManager - initializeData called, mode:', mode, 'isInitializing:', this.isInitializing)

    if (this.isInitializing) {
      console.log('ProcessDetailDataManager - already initializing, skipping...')
      return
    }

    if (!displayData) {
      // 即使没有数据也要通知回调，以便UI能正确响应
      this.callbacks.onDataChange?.(this.data)
      return
    }

    // 检查是否已经在初始化中，避免重复调用
    if (this.data.dataLoaded.form && this.data.dataLoaded.history && this.data.dataLoaded.status) {
      console.log('ProcessDetailDataManager - data already loaded, skipping initialization')
      return
    }

    console.log('ProcessDetailDataManager - starting data initialization...')
    this.isInitializing = true

    try {
      await Promise.all([
        this.loadFormData(displayData, mode),
        this.loadApprovalHistory(displayData),
        this.loadNodeStatus(displayData)
      ])

      // 加载下一节点配置（需要表单数据）
      // 所有模式都需要加载下一节点，用于流程图显示
      const formData = this.data.formData?.formData || {}
      await this.loadNextNodes(displayData, formData, mode)

      console.log('ProcessDetailDataManager - data initialization completed')
      this.callbacks.onDataChange?.(this.data)
    } catch (error) {
      console.error('ProcessDetailDataManager - initialization failed:', error)
    } finally {
      this.isInitializing = false
    }
  }

  // 加载表单数据
  async loadFormData(displayData: any, mode: string) {
    if (this.data.dataLoaded.form) {
      return
    }

    let processId = displayData?.processId || displayData?.id

    // 如果是任务模式且没有processId，尝试从processInstanceId获取
    if (!processId && mode === 'task' && displayData?.processInstanceId) {
      // 这里需要根据processInstanceId获取流程信息
      // 暂时使用模拟数据，实际应该调用API获取
      console.log('任务模式，从processInstanceId获取流程信息:', displayData.processInstanceId)

      // 模拟数据，实际应该调用API
      if (displayData.processInstanceId === 'PI_001') {
        processId = 'process_001'
      } else if (displayData.processInstanceId === 'PI_002') {
        processId = 'process_002'
      }
    }

    // 如果是view模式（查看流程详情），尝试从processInstanceId获取流程信息
    if (!processId && mode === 'view' && displayData?.processInstanceId) {
      console.log('查看模式，从processInstanceId获取流程信息:', displayData.processInstanceId)

      // 模拟数据，实际应该调用API
      if (displayData.processInstanceId === 'PI_001') {
        processId = 'process_001'
      } else if (displayData.processInstanceId === 'PI_002') {
        processId = 'process_002'
      }
    }

    if (!processId) {
      console.warn('无法获取processId，跳过表单数据加载')
      this.data.formData = null
      this.data.dataLoaded.form = true
      return
    }

    try {
      const formRes = await getProcessFormBindList({ processId: processId })

      let bindData: any = null
      if (formRes && Array.isArray(formRes)) {
        if (formRes.length > 0) {
          bindData = formRes[0]
        } else {
          this.data.formData = null
          this.data.dataLoaded.form = true
          return
        }
      } else if (formRes && formRes.data && Array.isArray(formRes.data)) {
        if (formRes.data.length > 0) {
          bindData = formRes[0]
        } else {
          this.data.formData = null
          this.data.dataLoaded.form = true
          return
        }
      } else {
        this.data.formData = null
        this.data.dataLoaded.form = true
        return
      }

      // 获取表单详细信息
      if (bindData?.formId) {
        try {
          const formDetailRes = await getFormDetail(bindData.formId)

          let formDetail: any = null
          if (formDetailRes && formDetailRes.data) {
            formDetail = formDetailRes.data
          } else if (formDetailRes && formDetailRes.code === 200) {
            formDetail = formDetailRes
          } else {
            formDetail = formDetailRes
          }

          if (formDetail) {
            this.data.formData = {
              ...bindData,
              formDetail: formDetail,
              formSchema: formDetail.formSchema,
              name: formDetail.name || bindData.formName
            }

            // 如果是任务模式或查看模式，尝试获取已保存的表单数据
            if ((mode === 'task' || mode === 'view') && displayData?.processInstanceId) {
              try {
                if (displayData.formData) {
                  try {
                    const instanceFormData = typeof displayData.formData === 'string'
                      ? JSON.parse(displayData.formData)
                      : displayData.formData
                    this.data.formData.formData = instanceFormData
                    console.log('从displayData.formData加载表单数据:', instanceFormData)
                  } catch (parseError) {
                    console.warn('解析displayData.formData失败，尝试从数据库加载:', parseError)
                    await this.loadFormDataFromTable(displayData)
                  }
                } else {
                  console.log('displayData.formData为空，从数据库加载表单数据')
                  await this.loadFormDataFromTable(displayData)
                }
              } catch (error) {
                // 不影响表单配置的加载
                console.warn('加载表单数据失败:', error)
              }
            }
          } else {
            this.data.formData = bindData
          }
        } catch (error) {
          console.warn('获取表单详情失败:', error)
          this.data.formData = bindData
        }
      } else {
        this.data.formData = bindData
      }

      this.data.dataLoaded.form = true
    } catch (error) {
      console.error('加载表单数据失败:', error)
      this.data.formData = null
      this.data.dataLoaded.form = true
    }
  }

  // 从wf_form_data表加载表单数据
  async loadFormDataFromTable(displayData: any) {
    const processInstanceId = displayData?.processInstanceId
    if (!processInstanceId) {
      return
    }

    try {
      const formDataRes = await getFormDataByInstanceId(processInstanceId)

      let tableFormData: any = null
      if (formDataRes && Array.isArray(formDataRes) && formDataRes.length > 0) {
        tableFormData = formDataRes[0]
      } else {
        return
      }

      if (tableFormData) {
        try {
          const parsedFormData = typeof tableFormData.formData === 'string'
            ? JSON.parse(tableFormData.formData)
            : tableFormData.formData
          this.data.formData.formData = parsedFormData
        } catch (parseError) {
          // 解析失败，忽略
        }
      }
    } catch (error) {
      // 加载失败，忽略
    }
  }

  // 加载流程图数据
  async loadGraphData(displayData: any) {
    if (this.data.dataLoaded.diagram) {
      return
    }

    let processId = displayData?.processId || displayData?.id
    const processVersionId = displayData?.processVersionId

    // 如果是任务模式且没有processId，尝试从processInstanceId获取
    if (!processId && displayData?.processInstanceId) {
      // 这里需要根据processInstanceId获取流程信息
      // 暂时使用模拟数据，实际应该调用API获取
      console.log('从processInstanceId获取流程信息:', displayData.processInstanceId)

      // 模拟数据，实际应该调用API
      if (displayData.processInstanceId === 'PI_001') {
        processId = 'process_001'
      } else if (displayData.processInstanceId === 'PI_002') {
        processId = 'process_002'
      }
    }

    if (!processId && !processVersionId) {
      console.warn('无法获取processId或processVersionId，使用默认流程图数据')
      this.data.graphData = this.getDefaultGraphData()
      this.data.dataLoaded.diagram = true
      return
    }

    try {
      let versionRes: any = null

      if (processVersionId) {
        versionRes = await getProcessVersionById(processVersionId)
      } else {
        versionRes = await getProcessVersion(processId)
      }

      let versionData: any = null
      if (versionRes && versionRes.data) {
        versionData = versionRes.data
      } else if (versionRes && versionRes.code === 200) {
        versionData = versionRes
      } else {
        versionData = versionRes
      }

      if (versionData && versionData.graphSchema) {
        try {
          const graphSchema = typeof versionData.graphSchema === 'string'
            ? JSON.parse(versionData.graphSchema)
            : versionData.graphSchema

          this.data.graphData = {
            nodes: graphSchema.nodes || [],
            edges: graphSchema.edges || []
          }
        } catch (error) {
          console.warn('解析流程图数据失败，使用默认数据:', error)
          this.data.graphData = this.getDefaultGraphData()
        }
      } else {
        console.warn('未找到流程图数据，使用默认数据')
        this.data.graphData = this.getDefaultGraphData()
      }

      this.data.dataLoaded.diagram = true
    } catch (error) {
      console.error('加载流程图数据失败，使用默认数据:', error)
      this.data.graphData = this.getDefaultGraphData()
      this.data.dataLoaded.diagram = true
    }
  }

  // 获取默认流程图数据
  getDefaultGraphData() {
    return {
      nodes: [
        { id: 'start', label: '开始', type: 'start' },
        { id: 'task1', label: '任务1', type: 'task' },
        { id: 'task2', label: '任务2', type: 'task' },
        { id: 'end', label: '结束', type: 'end' }
      ],
      edges: [
        { source: 'start', target: 'task1' },
        { source: 'task1', target: 'task2' },
        { source: 'task2', target: 'end' }
      ]
    }
  }

  // 加载审批历史
  async loadApprovalHistory(displayData: any) {
    if (this.data.dataLoaded.history) {
      return
    }

    const processInstanceId = displayData?.processInstanceId || displayData?.id
    console.log('loadApprovalHistory - 开始加载审批历史，processInstanceId:', processInstanceId)

    if (!processInstanceId) {
      console.warn('loadApprovalHistory - processInstanceId为空，跳过审批历史加载')
      this.data.approvalHistory = []
      this.data.dataLoaded.history = true
      return
    }

    try {
      console.log('loadApprovalHistory - 调用API获取审批历史，processInstanceId:', processInstanceId)
      const res = await fetchApprovalHistory(processInstanceId)
      console.log('loadApprovalHistory - API响应:', res)

      let historyData: any[] = []
      if (res && res.data) {
        historyData = res.data || []
        console.log('loadApprovalHistory - 从res.data获取数据，数量:', historyData.length)
      } else if (res && Array.isArray(res)) {
        historyData = res
        console.log('loadApprovalHistory - 从res数组获取数据，数量:', historyData.length)
      } else if (res && res.code === 200) {
        historyData = res.data || []
        console.log('loadApprovalHistory - 从res.code=200获取数据，数量:', historyData.length)
      } else {
        console.warn('loadApprovalHistory - API响应格式异常:', res)
      }

      console.log('loadApprovalHistory - 原始审批历史数据:', historyData)

      // 处理审批历史数据，添加缺失的字段
      this.data.approvalHistory = historyData.map(record => {
        const processedRecord = {
          ...record,
          nodeName: record.nodeName || record.taskName || '未知节点',
          approver: record.approver || record.assignee || record.userName || '系统',
          approvalTime: record.approvalTime || record.createTime || record.completeTime,
          approvalResult: record.approvalResult || record.result || 'PASS',
          approvalOpinion: record.approvalOpinion || record.opinion || '',
          duration: record.duration || this.calculateDuration(record.createTime, record.completeTime)
        }
        console.log('loadApprovalHistory - 处理后的审批记录:', processedRecord)
        return processedRecord
      })

      console.log('loadApprovalHistory - 最终审批历史数据，数量:', this.data.approvalHistory.length)
      this.data.dataLoaded.history = true
    } catch (error) {
      console.error('loadApprovalHistory - 加载审批历史失败:', error)
      this.data.approvalHistory = []
      this.data.dataLoaded.history = true
    }
  }

  // 加载节点状态
  async loadNodeStatus(displayData: any) {
    if (this.data.dataLoaded.status) {
      return
    }

    const processInstanceId = displayData?.processInstanceId || displayData?.id
    if (!processInstanceId) {
      return
    }

    try {
      let nodeData: any[] = []
      try {
        const res = await getNodeStatus(processInstanceId)

        if (res && res.data) {
          nodeData = res.data || []
        } else if (res && Array.isArray(res)) {
          nodeData = res
        } else if (res && res.code === 200) {
          nodeData = res.data || []
        }
      } catch (apiError) {
        // API调用失败，使用基于任务数据的模拟数据
      }

      // 如果API没有返回数据，基于任务数据生成节点状态
      if (!nodeData || nodeData.length === 0) {
        const taskData = displayData

        if (taskData) {
          nodeData = [
            {
              nodeName: '开始节点',
              nodeType: 'startEvent',
              taskType: 'startEvent',
              status: 'COMPLETED',
              assignee: '系统',
              userName: '系统',
              approver: '系统',
              startTime: new Date(Date.now() - 3600000).toISOString(),
              endTime: new Date(Date.now() - 3595000).toISOString(),
              createTime: new Date(Date.now() - 3600000).toISOString(),
              completeTime: new Date(Date.now() - 3595000).toISOString(),
              duration: '5秒',
              description: '流程启动节点'
            },
            {
              nodeName: taskData.taskName || taskData.nodeName || '用户任务',
              nodeType: 'userTask',
              taskType: 'userTask',
              status: taskData.status === 'PENDING' ? 'ACTIVE' : taskData.status,
              assignee: taskData.assignee || 'admin',
              userName: taskData.assignee || 'admin',
              approver: taskData.assignee || 'admin',
              startTime: taskData.createTime ? new Date(taskData.createTime).toISOString() : new Date(Date.now() - 3000000).toISOString(),
              endTime: null,
              createTime: taskData.createTime ? new Date(taskData.createTime).toISOString() : new Date(Date.now() - 3000000).toISOString(),
              completeTime: null,
              duration: null,
              description: `任务ID: ${taskData.taskId || taskData.id}`,
              taskDefinitionKey: taskData.taskDefinitionKey,
              nodeId: taskData.nodeId
            }
          ]

          if (taskData.status === 'COMPLETED') {
            nodeData.push({
              nodeName: '结束节点',
              nodeType: 'endEvent',
              taskType: 'endEvent',
              status: 'PENDING',
              assignee: null,
              userName: null,
              approver: null,
              startTime: null,
              endTime: null,
              createTime: null,
              completeTime: null,
              duration: null,
              description: '流程结束节点'
            })
          }
        } else {
          nodeData = [
            {
              nodeName: '开始节点',
              nodeType: 'startEvent',
              taskType: 'startEvent',
              status: 'COMPLETED',
              assignee: '系统',
              userName: '系统',
              approver: '系统',
              startTime: new Date(Date.now() - 3600000).toISOString(),
              endTime: new Date(Date.now() - 3595000).toISOString(),
              createTime: new Date(Date.now() - 3600000).toISOString(),
              completeTime: new Date(Date.now() - 3595000).toISOString(),
              duration: '5秒',
              description: '流程启动节点'
            },
            {
              nodeName: '用户任务1',
              nodeType: 'userTask',
              taskType: 'userTask',
              status: 'ACTIVE',
              assignee: 'admin',
              userName: 'admin',
              approver: 'admin',
              startTime: new Date(Date.now() - 3000000).toISOString(),
              endTime: null,
              createTime: new Date(Date.now() - 3000000).toISOString(),
              completeTime: null,
              duration: null,
              description: '审批任务节点'
            },
            {
              nodeName: '网关节点',
              nodeType: 'exclusiveGateway',
              taskType: 'exclusiveGateway',
              status: 'WAITING',
              assignee: null,
              userName: null,
              approver: null,
              startTime: null,
              endTime: null,
              createTime: null,
              completeTime: null,
              duration: null,
              description: '条件判断节点'
            },
            {
              nodeName: '用户任务2',
              nodeType: 'userTask',
              taskType: 'userTask',
              status: 'PENDING',
              assignee: 'manager',
              userName: 'manager',
              approver: 'manager',
              startTime: null,
              endTime: null,
              createTime: null,
              completeTime: null,
              duration: null,
              description: '经理审批节点'
            },
            {
              nodeName: '结束节点',
              nodeType: 'endEvent',
              taskType: 'endEvent',
              status: 'PENDING',
              assignee: null,
              userName: null,
              approver: null,
              startTime: null,
              endTime: null,
              createTime: null,
              completeTime: null,
              duration: null,
              description: '流程结束节点'
            }
          ]
        }
      }

      // 处理节点状态数据，确保字段一致性
      this.data.nodeStatusList = nodeData.map(node => ({
        ...node,
        nodeName: node.nodeName || node.name || '未知节点',
        taskType: node.taskType || node.nodeType || 'unknown',
        status: node.status || 'PENDING',
        assignee: node.assignee || node.userName || node.approver || '-',
        createTime: node.createTime || node.startTime,
        completeTime: node.completeTime || node.endTime,
        duration: node.duration || this.calculateDuration(node.createTime, node.completeTime)
      }))

      this.data.dataLoaded.status = true
    } catch (error) {
      this.data.nodeStatusList = [
        {
          nodeName: '开始节点',
          nodeType: 'startEvent',
          taskType: 'startEvent',
          status: 'COMPLETED',
          assignee: '系统',
          userName: '系统',
          approver: '系统',
          startTime: new Date().toISOString(),
          endTime: new Date(Date.now() + 5000).toISOString(),
          createTime: new Date().toISOString(),
          completeTime: new Date(Date.now() + 5000).toISOString(),
          duration: '5秒'
        }
      ]
      this.data.dataLoaded.status = true
    }
  }

  // 加载下一节点配置
  async loadNextNodes(displayData: any, formData: any, mode: string) {
    console.log('ProcessDetailDataManager - loadNextNodes called, mode:', mode, 'dataLoaded:', this.data.dataLoaded.nextNodes)

    if (this.data.dataLoaded.nextNodes) {
      console.log('ProcessDetailDataManager - nextNodes already loaded, skipping...')
      return
    }

    try {
      let requestData: any = {}

      if (mode === 'start') {
        // 发起模式
        requestData = {
          processId: displayData?.processId || displayData?.id,
          processKey: displayData?.processKey,
          formData: formData || {}
        }
        console.log('ProcessDetailDataManager - start mode requestData:', requestData)
      } else if (mode === 'task') {
        // 任务处理模式
        const taskId = displayData?.taskId || displayData?.id
        const processInstanceId = displayData?.processInstanceId

        if (!taskId || !processInstanceId) {
          console.warn('ProcessDetailDataManager - 任务模式缺少必要参数，taskId:', taskId, 'processInstanceId:', processInstanceId)
          this.data.nextNodes = []
          this.data.dataLoaded.nextNodes = true
          return
        }

        requestData = {
          taskId: taskId,
          processInstanceId: processInstanceId,
          formData: formData || {}
        }
        console.log('ProcessDetailDataManager - task mode requestData:', requestData)
      } else {
        // view模式也需要加载下一节点，用于流程图显示
        console.log('ProcessDetailDataManager - view mode, attempting to load nextNodes for diagram display')
        
        // 尝试从displayData中获取必要信息
        const processInstanceId = displayData?.processInstanceId || displayData?.id
        const processId = displayData?.processId
        
        if (processInstanceId) {
          // 如果有流程实例ID，尝试获取下一节点信息
          requestData = {
            processInstanceId: processInstanceId,
            processId: processId,
            formData: formData || {}
          }
          console.log('ProcessDetailDataManager - view mode requestData:', requestData)
        } else {
          console.log('ProcessDetailDataManager - view mode missing processInstanceId, skipping nextNodes load')
          this.data.nextNodes = []
          this.data.dataLoaded.nextNodes = true
          return
        }
      }

      console.log('ProcessDetailDataManager - calling getNextNodes API...')
      const response = await getNextNodes(requestData)
      console.log('ProcessDetailDataManager - getNextNodes API response:', response)

      let nextNodesList: any[] = []
      if (response && Array.isArray(response) && response.length > 0) {
        nextNodesList = response
      } else if (response && response.data && Array.isArray(response.data)) {
        nextNodesList = response.data
      } else if (response && response.code === 200 && response.data) {
        nextNodesList = Array.isArray(response.data) ? response.data : []
      }

      console.log('ProcessDetailDataManager - processed nextNodesList:', nextNodesList)

      // 处理下一节点数据，添加默认配置
      this.data.nextNodes = nextNodesList.map(node => ({
        ...node,
        id: node.id || node.nodeId,
        name: node.name || node.nodeName || '未知节点',
        type: node.type || node.nodeType || 'unknown',
        handlers: node.handlers || [],
        handlerType: node.handlerType || 'user'
      }))

      this.data.dataLoaded.nextNodes = true
      console.log('ProcessDetailDataManager - nextNodes loaded successfully, count:', this.data.nextNodes.length)
    } catch (error) {
      console.error('ProcessDetailDataManager - 加载下一节点配置失败:', error)
      this.data.nextNodes = []
      this.data.dataLoaded.nextNodes = true
    }
  }

  // 懒加载流程图数据
  async loadDiagramData(displayData: any) {
    if (this.data.diagramLoaded) {
      return
    }

    await this.loadGraphData(displayData)
    this.data.diagramLoaded = true
    this.callbacks.onDataChange?.(this.data)
  }

  // 刷新所有数据
  async refreshAllData(displayData: any, mode: string) {
    this.resetData()
    await this.initializeData(displayData, mode)
    this.callbacks.onDataChange?.(this.data)
  }

  // 计算耗时
  calculateDuration(startTime: string, endTime: string) {
    if (!startTime || !endTime) return '-'
    try {
      const start = new Date(startTime)
      const end = new Date(endTime)
      const diff = end.getTime() - start.getTime()

      if (diff < 0) return '-'

      const seconds = Math.floor(diff / 1000)
      const minutes = Math.floor(seconds / 60)
      const hours = Math.floor(minutes / 60)
      const days = Math.floor(hours / 24)

      if (days > 0) return `${days}天`
      if (hours > 0) return `${hours}小时`
      if (minutes > 0) return `${minutes}分钟`
      return `${seconds}秒`
    } catch (error) {
      return '-'
    }
  }

  // 获取节点类型文本
  getNodeTypeText(type: string) {
    const typeMap: Record<string, string> = {
      'startEvent': '开始事件',
      'userTask': '用户任务',
      'serviceTask': '服务任务',
      'scriptTask': '脚本任务',
      'exclusiveGateway': '排他网关',
      'parallelGateway': '并行网关',
      'inclusiveGateway': '包容网关',
      'endEvent': '结束事件',
      'intermediateCatchEvent': '中间捕获事件',
      'intermediateThrowEvent': '中间抛出事件',
      'boundaryEvent': '边界事件'
    }
    return typeMap[type] || type
  }

  // 获取节点状态类型
  getNodeStatusType(status: string) {
    const statusMap: Record<string, string> = {
      'COMPLETED': 'success',
      'ACTIVE': 'primary',
      'PENDING': 'warning',
      'WAITING': 'info',
      'CANCELLED': 'danger',
      'SUSPENDED': 'warning'
    }
    return statusMap[status] || 'info'
  }

  // 获取节点状态文本
  getNodeStatusText(status: string) {
    const statusMap: Record<string, string> = {
      'COMPLETED': '已完成',
      'ACTIVE': '进行中',
      'PENDING': '待处理',
      'WAITING': '等待中',
      'CANCELLED': '已取消',
      'SUSPENDED': '已暂停'
    }
    return statusMap[status] || status
  }

  // 获取审批结果类型
  getApprovalResultType(result: string) {
    const typeMap: Record<string, string> = {
      'PASS': 'success',
      'REJECT': 'danger',
      'TRANSFER': 'warning',
      'CC': 'info',
      'APPROVED': 'success',
      'REJECTED': 'danger',
      'TRANSFERRED': 'warning'
    }
    return typeMap[result] || 'info'
  }

  // 获取审批结果文本
  getApprovalResultText(result: string) {
    const textMap: Record<string, string> = {
      'PASS': '通过',
      'REJECT': '拒绝',
      'TRANSFER': '转办',
      'CC': '抄送',
      'APPROVED': '已通过',
      'REJECTED': '已拒绝',
      'TRANSFERRED': '已转办'
    }
    return textMap[result] || result
  }

  // 格式化日期时间
  formatDateTime(dateTime: string) {
    if (!dateTime) return '-'
    try {
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    } catch (error) {
      return dateTime
    }
  }

  // 发起流程
  async startProcess(displayData: any, formData: any, assigneeConfig: any) {
    console.log('processDetailDataManager - startProcess 开始')
    console.log('processDetailDataManager - displayData:', displayData)
    console.log('processDetailDataManager - formData:', formData)
    console.log('processDetailDataManager - assigneeConfig:', assigneeConfig)
    
    try {
      // 进一步简化参数，只传递必要的数据
      const startParams: any = {
        // 只传递processId，其他信息由后端查询获取
        processId: displayData?.processId || displayData?.id,
        // 表单数据（必传）
        formData: formData,
      }
      
      // 只有在人员配置被展开过时才传递 assigneeConfig
      if (assigneeConfig && Array.isArray(assigneeConfig) && assigneeConfig.length > 0) {
        startParams.assigneeConfig = assigneeConfig
        console.log('人员配置已展开过，传输 assigneeConfig:', assigneeConfig)
      } else {
        console.log('人员配置未展开过，不传输 assigneeConfig，后端将使用流程版本中的默认配置')
      }
      
      console.log('发起流程参数:', startParams)
      const result = await startProcessApi(startParams)
      
      if (result && result.code === 200) {
        console.log('流程发起成功:', result)
        return result
      } else {
        ElMessage.error(result?.msg || '流程发起失败')
        console.error('流程发起失败:', result)
        return null
      }
    } catch (error) {
      console.error('发起流程异常:', error)
      ElMessage.error('发起流程异常: ' + (error as Error).message)
      return null
    }
  }

  // 提交审批
  async submitApproval(displayData: any, approvalData: any) {
    try {

      // 尝试从多个可能的字段获取taskId
      const taskId = displayData?.taskId || displayData?.id || approvalData?.taskId

      // 验证taskId是否存在
      if (!taskId) {
        console.error('submitApproval - taskId为空，displayData:', displayData)
        throw new Error('任务ID不能为空')
      }

      const submitData: any = {
        taskId: taskId,
        processInstanceId: displayData?.processInstanceId,
        approvalResult: approvalData.approvalForm.approvalResult,
        approvalOpinion: approvalData.approvalForm.approvalOpinion,
        nextNodes: approvalData.nextNodes,
        // 添加assigneeConfig支持，与发起流程保持一致
        assigneeConfig: approvalData.assigneeConfig
      }

      // 如果是转办，添加转办人员信息
      if (approvalData.approvalForm.approvalResult === 'TRANSFER' && approvalData.transferAssignee) {
        submitData.transferAssignee = approvalData.transferAssignee
      }

      console.log('submitApproval - 发送给后端的数据:', submitData)

      const result = await submitApprovalApi(submitData)

      // 修复：检查返回结果的结构，支持多种返回格式
      let isSuccess = false
      let resultData = null
      let errorMsg = '审批提交失败'

      if (result) {
        // 检查不同的返回格式
        if (result.code === 200) {
          isSuccess = true
          // 如果data字段存在且不为undefined，使用data，否则使用整个response
          resultData = result.data !== undefined ? result.data : result
        } else if (result.msg && result.type === 'success') {
          // 处理 {"msg":"审核提交成功","code":200,"type":"success"} 格式
          isSuccess = true
          resultData = result
        } else if (typeof result === 'object' && result.success !== undefined) {
          isSuccess = result.success
          resultData = result.data || result
          errorMsg = result.message || result.msg || '审批提交失败'
        } else if (Array.isArray(result) || typeof result === 'object') {
          // 如果直接返回数据对象或数组，认为是成功的
          isSuccess = true
          resultData = result
        }
      }

      if (isSuccess) {
        ElMessage.success('审批提交成功')
        this.callbacks.onSuccess?.('submit-approval', resultData)
        return resultData
      } else {
        ElMessage.error(errorMsg)
        this.callbacks.onError?.('submit-approval', errorMsg)
        throw new Error(errorMsg)
      }
    } catch (error) {
      console.error('提交审批失败:', error)
      const errorMessage = error instanceof Error ? error.message : '审批提交失败'
      ElMessage.error(errorMessage)
      this.callbacks.onError?.('submit-approval', error)
      throw error
    }
  }
}

// 创建单例实例
export const processDetailDataManager = new ProcessDetailDataManager()
